package com.example.black.myapplication.shader;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.BitmapShader;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Rect;
import android.graphics.Shader;
import android.graphics.drawable.ShapeDrawable;
import android.graphics.drawable.shapes.OvalShape;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;

import com.example.black.myapplication.R;

/**
 * <pre>
 *     author : 28476
 *     e-mail : hao.wang@1hai.cn
 *     time   : 2019/01/03/16:34
 *     desc   : 总得理解：
 *     在一个bitmap上创建一个缩放后的bitmap覆盖在该图片上面
 *     1.canvas.drawBitmap 绘制一个原本的bitmap
 *     2.使用BitmapShader配合ShapeDrawable
 *     version: 1.0
 * </pre>
 */

public class ZoomImageView extends View {

    private static final int FACTOR = 3;//放大倍数
    private static final int RADIUS = 100;
    private Bitmap bitmap;
    private ShapeDrawable shapeDrawable;
    private Matrix matrix;

    public ZoomImageView(Context context) {
        super(context);
        initConfig();
    }
    public ZoomImageView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        initConfig();
    }

    public ZoomImageView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initConfig();
    }
    private void initConfig() {
        bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.icon2);
        Bitmap bmp = bitmap;
        //创建一个缩放后的bitmap
        bmp = Bitmap.createScaledBitmap(bmp,bmp.getWidth()*FACTOR,bmp.getHeight()*FACTOR,true);
        //传入放大之后的bmp，渲染出来才是放大之后的内容
        BitmapShader bitmapShader = new BitmapShader(bmp,Shader.TileMode.CLAMP,Shader.TileMode.CLAMP);
        shapeDrawable = new ShapeDrawable(new OvalShape());
        shapeDrawable.getPaint().setShader(bitmapShader);
        //截取缩放后bmp的一定的一个矩形区域
        shapeDrawable.setBounds(new Rect(0,0,RADIUS*2,RADIUS*2));
        matrix = new Matrix();
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        canvas.drawBitmap(bitmap,0,0,null);
        shapeDrawable.draw(canvas);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        int x = (int) event.getX();
        int y = (int) event.getY();//坐标作为圆心
        //平移的坐标要与缩放结合才是真实坐标点，此位置和区域指定的是要渲染出来的部分位置和大小（注意：这个是指的是在缩放后的bitmap上的坐标系）
        matrix.setTranslate(RADIUS- x * FACTOR,RADIUS - y * FACTOR);
        shapeDrawable.getPaint().getShader().setLocalMatrix(matrix);
        //该坐标作为圆心，这个drawable的范围就是上下左右加半径；绘制在实际bitmap上的一个区域位置和大小
        shapeDrawable.setBounds(x-RADIUS,y - RADIUS,x+RADIUS,y+RADIUS);
        invalidate();
        return true;
    }
}
